﻿Imports System.Xml.Serialization
Imports System.Text.RegularExpressions

Public Class SiteConfig
    Inherits DefaultConfig
    Private Shared mConfigInfo As New SiteConfigInfo
    Private Shared mConfigFilePath As String
    Private Shared mFileDateTime As DateTime

    REM 配置文件路径
    Public Overloads Shared ReadOnly Property ConfigFilePath() As String
        Get
            If String.IsNullOrEmpty(mConfigFilePath) OrElse Not IO.File.Exists(mConfigFilePath) Then

                Dim Path As String = AppSettings("ConfigPath")
                If Not Path.EndsWith("/") Then Path = String.Concat(Path, "/")
                mConfigFilePath = String.Format("{0}siteconfig.config", Path)

                If Not System.Web.HttpContext.Current Is Nothing Then
                    mConfigFilePath = System.Web.HttpContext.Current.Server.MapPath(mConfigFilePath)
                End If

            End If
            Return mConfigFilePath
        End Get
    End Property

    Public Shared Function Load() As SiteConfigInfo
        Return Load(False)
    End Function

    Public Shared Function Load(ByVal checktime As Boolean) As SiteConfigInfo
        mErrMessage = Nothing
        Try
            mConfigInfo = CType(LoadConfig(mFileDateTime, ConfigFilePath, mConfigInfo, checktime), SiteConfigInfo)

        Catch ex As Exception
            mErrMessage = ex.Message
            mConfigInfo = New SiteConfigInfo
        End Try
        Return mConfigInfo
    End Function

    Public Shared Sub Save()
        SaveConfig()
    End Sub

    Shared Sub New()

    End Sub
End Class

<Serializable()> <XmlRoot("SiteConfig")> Public Class SiteConfigInfo
    Implements IConfigInfo
    Private CurrentName As String
    <XmlElement("SiteInfo")> Public SiteInfos() As SiteInfo = {}

    Public Function Item(ByVal domain As String) As SiteInfo
        CurrentName = domain
        If SiteInfos Is Nothing OrElse SiteInfos.Length = 0 Then Return Nothing
        Return Array.Find(SiteInfos, AddressOf FindWhere)
    End Function

    Private Function FindWhere(ByVal item As SiteInfo) As Boolean
        Return Regex.IsMatch(CurrentName, item.Domain)
    End Function

    Protected Overrides Sub Finalize()
        'Accounts = Nothing
        MyBase.Finalize()
    End Sub
End Class


<Serializable()> Public Class SiteInfo
    Public Domain As String
    <XmlElement("Param")> Public Params() As ParamItem = {}    '其他附加配置的参数

    Public Function Item(ByVal name As String) As String
        For Each p As ParamItem In Params
            If p.field = name Or p.name = name Then
                Return p.Value
            End If
        Next
        Return String.Empty
    End Function

End Class





